package com.foo.common.base.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class FooGenericDaoImpl implements FooGenericDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Get the current Hibernate session
	 */
	@Override
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public Object get(Class<?> clazz, Serializable id) {
		return getSession().get(clazz, id);
	}

	@Override
	public Serializable save(Object object) {
		return getSession().save(object);
	}

	@Override
	public <T> void batchSave(List<T> object) {
		Session session = getSession();
		for (int i = 0; i < object.size(); i++) {
			session.save(object.get(i));
			if (i % 20 == 0) { // 20, same as the JDBC batch size
				// flush a batch of inserts and release memory:
				session.flush();
				session.clear();
			}
		}
	}

	@Override
	public void delete(Object object) {
		getSession().delete(object);
	}

	@Override
	public void delete(String entityName, Object object) {
		getSession().delete(entityName, object);
	}

	@Override
	public Serializable save(String entityName, Object object) {
		return getSession().save(entityName, object);
	}

	@Override
	public void saveOrUpdate(Object object) {
		getSession().saveOrUpdate(object);
	}

	@Override
	public <T> Object load(Class<T> theClass, Serializable id) {
		return getSession().load(theClass, id);
	}

	@Override
	public void saveOrUpdate(String entityName, Object object) {
		getSession().saveOrUpdate(entityName, object);
	}

	@Override
	public void update(Object object) {
		getSession().update(object);
	}

	@Override
	public void update(String entityName, Object object) {
		getSession().update(entityName, object);
	}

	@Override
	public void flush() throws HibernateException {
		getSession().flush();
	}

	@Override
	public void clear() {
		getSession().clear();
	}

}
